<template>
  <div class="page-container">
    <header>
      <img class="logo" src="@/assets/logo.png" />
      <span class="title">联盟商城</span>
    </header>
    <div class="login-wrapper">
      <div class="form-title">账号登录</div>
      <div class="form-wrapper">
        <el-form ref="loginFormRef" :model="loginData" :rules="loginRules">
          <el-form-item prop="username">
            <div class="form-item">
              <el-icon color="#666"><Lock /></el-icon>
              <el-input link v-model="loginData.username" placeholder="请输入账号" />
            </div>
          </el-form-item>

          <el-form-item prop="password">
            <div class="form-item">
              <el-icon color="#666"><Lock /></el-icon>
              <el-input type="password" v-model="loginData.password" show-password placeholder="请输入密码" />
            </div>
          </el-form-item>

          <el-form-item prop="captchaCode">
            <div class="form-item">
              <el-icon color="#666"><Lock /></el-icon>
              <el-input link v-model="loginData.captchaCode" placeholder="请输入验证码" @keyup.enter="handleLogin" />
              <el-image @click="getCaptcha" :src="captchaBase64" class="cursor-pointer w-[120px] h-[30px]" />
            </div>
          </el-form-item>
        </el-form>

        <div class="tools">
          <el-checkbox v-model="isRememberPassword" acti label="记住密码" />
          <span class="forget-password">忘记密码</span>
        </div>

        <div class="btn-wrapper">
          <el-button type="primary" class="login-btn" :loading="isLoginLoading" @click="handleLogin">登录</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import AuthAPI from '@/api/auth'
import { LoginData } from '@/api/auth/model'
import { useUserStore } from '@/store'
import { FormInstance } from 'element-plus'
import { LocationQuery } from 'vue-router'

defineOptions({
  name: 'Login',
})

const route = useRoute()
const userStore = useUserStore()
const router = useRouter()

const loginFormRef = ref<FormInstance>() // 登录表单ref
const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入账号',
      },
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入密码',
      },
      {
        min: 6,
        message: '密码最小为6位',
        trigger: 'blur',
      },
    ],
    code: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入验证码',
      },
    ],
  }
})

const loginData = ref<LoginData>({
  username: 'admin',
  password: '123456',
})
const captchaBase64 = ref('')
const isRememberPassword = ref(false) // 记住密码
const isLoginLoading = ref(false)

onMounted(() => {
  getCaptcha()
})

/** 获取验证码 */
function getCaptcha() {
  AuthAPI.getCaptcha().then(data => {
    loginData.value.captchaKey = data.captchaKey
    captchaBase64.value = data.captchaBase64
  })
}
// 登录
function handleLogin() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      isLoginLoading.value = true
      userStore
        .login(loginData.value)
        .then(() => {
          const { path, queryParams } = parseRedirect()
          router.push({ path: path, query: queryParams })
        })
        .catch(() => {
          getCaptcha()
        })
        .finally(() => {
          isLoginLoading.value = false
        })
    }
  })
}

// 解析 redirect 字符串 为 path 和  queryParams
function parseRedirect(): {
  path: string
  queryParams: Record<string, string>
} {
  const query: LocationQuery = route.query
  const redirect = (query.redirect as string) ?? '/'

  const url = new URL(redirect, window.location.origin)
  const path = url.pathname
  const queryParams: Record<string, string> = {}

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value
  })

  return { path, queryParams }
}
</script>

<style lang="scss" scoped>
.page-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-width: 1200px;
  min-height: 500px;
  background: url('@/assets/images/login-bg.png') no-repeat center / cover;
  overflow: hidden;
  header {
    display: flex;
    align-items: flex-start;
    padding: 28px 40px 0;
    user-select: none;
    .logo {
      width: 161px;
      height: 45px;
      pointer-events: none;
    }
    .title {
      margin-left: 12px;
      color: var(--el-color-primary);
      font-size: 24px;
      font-weight: bold;
    }
  }

  .login-wrapper {
    position: absolute;
    // top: 240px;
    top: 24%;
    right: 425px;
    padding: 36px 40px 77px;
    width: 390px;
    box-shadow: 0px 9px 40px 0px rgba(208, 103, 103, 0.25);
    background: rgba($color: #fff, $alpha: 0.8);
    border-radius: 8px;
    .form-title {
      font-size: 18px;
      text-align: center;
      user-select: none;
    }
    .form-wrapper {
      .login-form {
        width: 100%;
      }
      :deep(.el-form-item--default) {
        margin-bottom: 10px;
      }
      .form-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px 0;
        width: 100%;
        border-bottom: 1px solid #ddcdc8;
        :deep(.el-input__wrapper) {
          padding: 0;
          background: transparent;
          border: none;
          box-shadow: none;
          outline: none;
        }
      }
      .tools {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: var(--el-color-primary);
        font-size: 14px;
        .forget-password {
          cursor: pointer;
          user-select: none;
        }
      }
      .btn-wrapper {
        margin-top: 50px;
        .login-btn {
          width: 100%;
          height: 40px;
          border-radius: 40px;
          border: none;
          outline: none;
        }
      }
    }
  }
}
</style>
